package com.handpay.zztong.hp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.DateUtils;
import com.handpay.zztong.hp.adapter.QueryAppealsAdapter;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.AppealInfo;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.paymentbill.widget.CalendarDialogView;
import com.handpay.zztong.hp.paymentbill.widget.CalendarView;
import com.handpay.zztong.hp.ui.DialogFactory;
import com.handpay.zztong.hp.ui.ZZTShowDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import se.krka.kahlua.vm.LuaTable;

/**
 * 交易查询
 *
 * @author yanglun
 */
public class QueryAppeals extends ZZTongActivity implements View.OnClickListener, CalendarView.OnItemClickListener {
    final private int QUERY_BILLS_REQ_CODE = 1;
    private boolean isDatePickerDialog4StartDate = false;
    private ZZTShowDialog<CalendarDialogView> mCalendarDialog;
    // 起始日期控件
    private TextView startDateShowTextView;
    // 结束日期控件
    private TextView endDateShowTextView;
    // 页码信息
    private TextView tvPageInfo;
    // 分页按钮
    private Button btnLast;
    private Button btnNext;
    private Button btnIndex;
    private Button btnEnd;
    // 起始日期
    private Date startDate;
    // 结束日期
    private Date endDate;
    // 交易账单列表
    private List<AppealInfo> appealInfos;
    // 总金额,总笔数
    private TextView tvAmounts, tvItems;

//    private boolean isQueryBills = false;
    /**
     * 交易账单listview
     */
    private ListView queryBillsListView;
    private LinearLayout queryBillsListViewFooterView;
    private static final String[] mAppealStatusType = {"全部", "已申诉待回复", "已回复 "};
    private Spinner appeal_status_spinner;
    private ArrayAdapter<String> mAappealStatusAdapter;
    private String mAppealStatus;// 交易状态

    private int pageNo = 1;
    private Double totalPages = -1d;
    /**
     * 交易账单listview adapter
     */
    private QueryAppealsAdapter queryAppealsAdapter;
    private QueryAppeals mContext;
    //	private boolean isQueryBills = false;
    private int curr_position = 0;

    @Override
    protected boolean isShownTopBar() {
        return true;
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.query_appeals_title), true);
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_querybills);
        super.onCreate(savedInstanceState);

        mContext = this;
        mCalendarDialog = new ZZTShowDialog<CalendarDialogView>(this, new CalendarDialogView(this), R.style.dialog);
        mCalendarDialog.getContentView().getCalendar().setOnItemClickListener(this);

        this.queryBillsListView = (ListView) findViewById(R.id.queryBillsListView);
        this.queryBillsListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                curr_position = arg2 - 1;
                AppealInfo appealInfo = appealInfos.get(arg2 - 1);
                Intent intent = new Intent();
                intent.setClass(mContext, AppealResponseActivity.class);
                intent.putExtra(ACTION, appealInfo);
                mContext.startActivity(intent);
            }
        });

        LayoutInflater inflater = LayoutInflater.from(this);
        this.queryBillsListViewFooterView = (LinearLayout) inflater.inflate(R.layout.layout_more_item, null);
        this.tvPageInfo = (TextView) queryBillsListViewFooterView.findViewById(R.id.tvPageInfo);
        this.btnIndex = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnIndex);
        this.btnEnd = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnEnd);
        this.btnLast = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnLast);
        this.btnNext = (Button) this.queryBillsListViewFooterView.findViewById(R.id.btnNext);
        this.btnIndex.setOnClickListener(this);
        this.btnEnd.setOnClickListener(this);
        this.btnLast.setOnClickListener(this);
        this.btnNext.setOnClickListener(this);
        this.queryBillsListView.addFooterView(this.queryBillsListViewFooterView);
        LinearLayout headerView = (LinearLayout) inflater.inflate(R.layout.query_appeals_zzt, null);
        headerView.findViewById(R.id.queryButton).setOnClickListener(this);
        headerView.findViewById(R.id.startDateRow).setOnClickListener(this);
        headerView.findViewById(R.id.endDateRow).setOnClickListener(this);
        appeal_status_spinner = (Spinner) headerView.findViewById(R.id.appeal_status_spinner);
        mAappealStatusAdapter = new ArrayAdapter<String>(this, R.layout.myspinnerdropdown, mAppealStatusType);
        appeal_status_spinner.setAdapter(mAappealStatusAdapter);
        // 添加事件Spinner事件监听
        appeal_status_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 0 已申诉待回复、1 已回复
                if (position == 0) {
                    mAppealStatus = null;
                } else if (position == 1) {
                    mAppealStatus = "0";// 已申诉待回复
                } else if (position == 2) {
                    mAppealStatus = "1";// 已回复，
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        Date today = DateUtils.formatStringToDate(DateUtils.formatDateToString(new Date(), "yyyyMMdd"), "yyyyMMdd");
        this.startDateShowTextView = (TextView) headerView.findViewById(R.id.startDateShowTextView);
        this.endDateShowTextView = (TextView) headerView.findViewById(R.id.endDateShowTextView);
        this.startDate = today;
        this.startDateShowTextView.setText(DateUtils.formatDateToString(startDate, "yyyy-MM-dd"));

        this.endDate = new Date(today.getTime() + (24 * 60 * 60 * 1000) - 1);
        this.endDateShowTextView.setText(DateUtils.formatDateToString(today, "yyyy-MM-dd"));

        this.queryBillsListView.addHeaderView(headerView);
        this.queryBillsListView.setAdapter(null);


    }

    /**
     * 发送交易查询请求
     */
    private void sendQueryRequest(int page) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("beginDate", DateUtils.formatDateToString(this.startDate, "yyyyMMddHHmmss"));
        params.put("endDate", DateUtils.formatDateToString(this.endDate, "yyyyMMddHHmmss"));
        params.put("pageSize", "5");
        params.put("pageNo", page + "");
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        if (mAppealStatus != null) {
            params.put("appealStatus", mAppealStatus);
        }
        doPost(this, Do_QueryAppeals, params);
    }

    // 成功获取数据handler
    private Handler queryBillsSuccessHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 通知adapter
            QueryAppeals.this.queryAppealsAdapter.notifyDataSetChanged();
            QueryAppeals.this.queryBillsListView.setVisibility(View.VISIBLE);
            QueryAppeals.this.closeProgressDialog();
        }
    };

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        if (super.netResponse(action, resp, showAlert) == true) {
            return true;
        }
        if (Do_QueryAppeals.equals(action)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData); // 获取到返回的数据
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);

            totalPages = (Double) luaTable.rawget("totalPages");
            totalPages = Double.valueOf(luaTable.rawget("totalPages").toString());
            LuaTable list = (LuaTable) luaTable.rawget("list");
            Vector<LuaTable> dataList = LuaTableUtil.getArray(list);

            if (list != null) {
                this.appealInfos = new ArrayList<AppealInfo>();
                this.queryAppealsAdapter = new QueryAppealsAdapter(this, this.appealInfos);
                this.queryBillsListView.setAdapter(this.queryAppealsAdapter);
                for (LuaTable appealData : dataList) {
                    AppealInfo appealInfo = CommonUtils.generateAppeal(appealData);
                    this.appealInfos.add(appealInfo);
                }
            }

            if (dataList == null || dataList.size() == 0) {
                this.showAlertDialog(this, R.string.tip, R.string.no_appeal_data);
                this.queryAppealsAdapter = new QueryAppealsAdapter(this, new ArrayList<AppealInfo>());
                this.queryBillsListView.setAdapter(this.queryAppealsAdapter);
                Log.i("result", curr_position + "");
                if (pageNo < 2) {
                    this.queryBillsListViewFooterView.setVisibility(View.GONE);
                }
                return false;
            }
            queryBillsListView.setSelection(curr_position);
            tvPageInfo.setText("第" + pageNo + "页" + "  共" + totalPages.intValue() + "页");
            queryBillsSuccessHandler.sendMessage(queryBillsSuccessHandler.obtainMessage());
            this.queryBillsListViewFooterView.setVisibility(View.VISIBLE);
            if (pageNo == 1) {
                btnLast.setEnabled(false);
            } else {
                btnLast.setEnabled(true);
            }
            if (pageNo == totalPages) {
                btnNext.setEnabled(false);
            } else {
                btnNext.setEnabled(true);
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int i = v.getId();
        if (i == R.id.startDateRow) {
            this.isDatePickerDialog4StartDate = true;
            mCalendarDialog.getContentView().setCalendarData(startDate);
            mCalendarDialog.show();
        } else if (i == R.id.endDateRow) {
            this.isDatePickerDialog4StartDate = false;
            mCalendarDialog.getContentView().setCalendarData(endDate);
            mCalendarDialog.show();
        } else if (i == R.id.queryButton || i == R.id.btnIndex) {
            pageNo = 1;
            doNet();

        } else if (i == R.id.btnNext) {
            pageNo++;
            doNet();

        } else if (i == R.id.btnLast) {
            pageNo--;
            doNet();

        } else if (i == R.id.btnEnd) {
            pageNo = totalPages.intValue();
            doNet();

        }

    }


    private void doNet() {
        if (this.startDate == null) {
            this.showAlertDialog(this, R.string.tip, R.string.select_start_date_tip);
            return;
        }
        if (this.endDate == null) {
            this.showAlertDialog(this, R.string.tip, R.string.select_end_date_tip);
            return;
        }
        if (startDate.after(endDate)) {
            this.showAlertDialog(this, R.string.tip, R.string.select_date_tip);
            return;
        }

        sendQueryRequest(pageNo);
    }


    private int getday(int year, int curr_moth) {
        int allday = 0;
        switch (curr_moth) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                allday = 31;
                break;
            case 2:
                allday = get2Days(year);
                break;
            default:
                allday = 30;
                break;
        }
        return allday;
    }

    public static int get2Days(int year)// 计算某一年2月份有多少天
    {
        Calendar c = Calendar.getInstance();
        c.set(year, 2, 1);// 0-11->1-12 将日期设置为某一年的3月1号
        c.add(Calendar.DAY_OF_MONTH, -1);// 将日期减去一天，即日期变成2月的最后一天
        return c.get(Calendar.DAY_OF_MONTH);// 返回二月最后一天的具体值
    }

    private boolean isDate() {
        if (this.startDate == null) {
            DialogFactory.showAlertDialog(this, R.string.tip, R.string.select_start_date_tip);
            return false;
        }
        if (this.endDate == null) {
            DialogFactory.showAlertDialog(this, R.string.tip, R.string.select_end_date_tip);
            return false;
        }
        if (startDate.after(endDate)) {
            DialogFactory.showAlertDialog(this, R.string.tip, R.string.select_date_tip);
            return false;
        }
        return true;
    }

    @Override

    public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
        mCalendarDialog.dismiss();
        if (this.isDatePickerDialog4StartDate) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            this.startDate = calendar.getTime();
            this.startDateShowTextView.setText(DateUtils.formatDateToString(startDate, "yyyy-MM-dd"));
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(downDate);
            this.endDate = new Date(calendar.getTimeInMillis() + (24 * 60 * 60 * 1000) - 1);
            this.endDateShowTextView.setText(DateUtils.formatDateToString(endDate, "yyyy-MM-dd"));
        }
    }
}
